package com.bluesky.framework.security.handler;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.http.ContentType;
import cn.hutool.json.JSONUtil;
import com.bluesky.common.result.R;
import com.bluesky.common.result.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 未登录处理器
 *
 * @author Kevin
 */
@Component
@Slf4j
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        e.printStackTrace();
        log.info("请求访问：{}，请求未授权，无法访问系统资源，{}", request.getRequestURI(), e.getLocalizedMessage());

        response.setCharacterEncoding(CharsetUtil.UTF_8);
        ServletUtil.write(response, JSONUtil.toJsonStr(R.result(ResultCode.UN_AUTHORIZED)), ContentType.JSON.toString());
    }
}
